package texture;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class DefaultResourcePack implements ResourcePack {
	private final static String defaultDomain=GLReferenceTexture.getDefaultDomain();
	private File fileAssets;
	private final Map<String, File> mapResourceFiles = new HashMap<>();
	
	public static final Set<String> defaultResourceDomains = new HashSet<String>(Arrays.asList(defaultDomain));

	public DefaultResourcePack(File fileAssets) {
		this.fileAssets = fileAssets;
		this.readAssetsDir(this.fileAssets);
	}

	private void readAssetsDir(File filePath) {
		if (filePath.isDirectory()) {
			File[] files = filePath.listFiles();
			int len = files.length;

			for (int i = 0; i < len; ++i) {
				File fileItem = files[i];
				this.readAssetsDir(fileItem);
			}
		} else {
			this.addResourceFile(AbstractResourcePack.getRelativeName(this.fileAssets, filePath), filePath);
		}
	}
	
	private void addResourceFile(String par1Str, File par2File) {
		this.mapResourceFiles.put((new ResourceLocation(par1Str)).toString(), par2File);
	}

	//---------------------------------------------------------------------todo
	


	@Override
	public Set<String> getResourceDomains() {
		return defaultResourceDomains;
	}

	public boolean resourceExists(ResourceLocation par1ResourceLocation) {
		return this.getResourceStream(par1ResourceLocation) != null || this.mapResourceFiles.containsKey(par1ResourceLocation.toString());
	}
	///assets/minecraft/textures/blocks/lava_flow.png.mcmeta
	///assets/minecraft/textures/blocks/lava_flow.png
	private InputStream getResourceStream(ResourceLocation par1ResourceLocation) {
		//System.out.println(fileAssets.getAbsolutePath());
		File file =new File(fileAssets,defaultDomain+"/" + par1ResourceLocation.getResourcePath());
		
		try {
			return new FileInputStream(file);
		} catch (FileNotFoundException e) {
			return null;
		}
		//return DefaultResourcePack.class.getResourceAsStream("/assets/"+defaultDomain+"/" + par1ResourceLocation.getResourcePath());
	}

	@Override
	public InputStream getInputStream(ResourceLocation par1ResourceLocation) throws IOException {
		InputStream inputstream = this.getResourceStream(par1ResourceLocation);

		if (inputstream != null) {
			return inputstream;
		} else {
			File file1 = (File) this.mapResourceFiles.get(par1ResourceLocation.toString());

			if (file1 != null) {
				return new FileInputStream(file1);
			} else {
				throw new FileNotFoundException(par1ResourceLocation.getResourcePath());
			}
		}
	}
}
